/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FrameResumo.java
 *
 * Created on 20/06/2010, 22:35:09
 */
package user_gui.contasresumidas;

import in_out.contasresumidas.GeraRelatorio;
import in_out.contasresumidas.LeOi;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.AbstractListModel;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.ListModel;
import javax.swing.filechooser.FileFilter;
import op.contasresumidas.ContaResumida;

/**
 *
 * @author Jônatas
 */
public class FrameResumo extends javax.swing.JFrame {

    /** Creates new form FrameResumo */
    public FrameResumo() {
        initComponents();
    }

    private void updateList() {
        ListModel model = new AbstractListModel() {

            public int getSize() {
                return arquivos.size();
            }

            public Object getElementAt(int index) {

                String[] elementos = new String[arquivos.size()];

                int i = 0;

                for (String elem : arquivos.keySet()) {
                    elementos[i++] = elem;
                }

                return elementos[index];
            }
        };

        jList1.setModel(model);

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Resumo de Contas");
        setResizable(false);

        jScrollPane1.setViewportView(jList1);

        jButton1.setText("Adicionar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Remover");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("OK");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 285, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 247, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 172, Short.MAX_VALUE)
                        .addComponent(jButton3)))
                .addContainerGap(42, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-416)/2, (screenSize.height-338)/2, 416, 338);
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        JFileChooser chooser = new JFileChooser();
        chooser.setFileFilter(new MyFilter());
        chooser.setMultiSelectionEnabled(true);
        chooser.showOpenDialog(this);

        File[] files = chooser.getSelectedFiles();

        for (File f : files) {
            arquivos.put(f.getName(), f);
        }

        updateList();

    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed

        Object[] objects = jList1.getSelectedValues();

        for (Object o : objects) {
            arquivos.remove(o.toString());
        }

        updateList();

    }//GEN-LAST:event_jButton2ActionPerformed

    private void trataErro(Exception e) {
        if (e instanceof IOException) {
            JOptionPane.showMessageDialog(this, "Houve um problema na leitura do arquivo, por favor verifique se este"
                    + "arquivo não está sendo utilizado por outra aplicação.", "Erro", JOptionPane.ERROR_MESSAGE);
        } else {
            JOptionPane.showMessageDialog(this, "Ocorreu um erro inesperado favor entre em contato"
                    + "com o suporte.", "Erro", JOptionPane.ERROR_MESSAGE);
        }

        e.printStackTrace();

        return;
    }

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed

       
        List<File> pdfs = new ArrayList<File>();
        List<File> txts = new ArrayList<File>();

        for (String key : arquivos.keySet()) {
            if (arquivos.get(key).getAbsolutePath().endsWith(".pdf")) {
                pdfs.add(arquivos.get(key));
            } else if (arquivos.get(key).getAbsolutePath().endsWith(".txt")) {
                txts.add(arquivos.get(key));
            }
        }

        List<ContaResumida> contas = new ArrayList<ContaResumida>();

        if (!pdfs.isEmpty()) {
            try {
                contas.addAll(LeOi.executePDF(pdfs));
            } catch (Exception ex) {
                trataErro(ex);
                return;
            }
        }

        if (!txts.isEmpty()) {
            try {
                contas.addAll(LeOi.executeTXT(txts));
            } catch (Exception ex) {
                trataErro(ex);
                return;
            }
        }

        ResumoOI resumo = new ResumoOI(contas);
        resumo.setVisible(true);

    }//GEN-LAST:event_jButton3ActionPerformed

    private Map<String, File> arquivos = new HashMap<String, File>();

    private class MyFilter extends FileFilter {

        @Override
        public boolean accept(File f) {

            if (f.isDirectory()) {
                return true;
            }

            return f.getName().endsWith(".txt") || f.getName().endsWith(".pdf");
        }

        @Override
        public String getDescription() {
            return "*.txt, *.pdf";
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JList jList1;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
}
